﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Text;
using System.Xml;
using System.Collections.Generic;
using System.Text;

namespace jader3rd.VsXmlSorter
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the information needed to show this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    // This attribute is needed to let the shell know that this package exposes some menus.
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(GuidList.guidVsXmlSorterPkgString)]
    public sealed class VsXmlSorterPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public VsXmlSorterPackage()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }



        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if ( null != mcs )
            {
                // Create the command for the menu item.
                CommandID menuCommandID = new CommandID(GuidList.guidVsXmlSorterCmdSet, (int)PkgCmdIDList.cmdidXmlSort);
                MenuCommand menuItem = new MenuCommand(MenuItemCallback, menuCommandID );
                mcs.AddCommand( menuItem );
            }
        }
        #endregion

        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
		{
			#region Generated
			/**
			// Show a Message Box to prove we were here
            IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
            Guid clsid = Guid.Empty;
            int result;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(
                       0,
                       ref clsid,
                       "VsXmlSorter",
                       string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.ToString()),
                       string.Empty,
                       0,
                       OLEMSGBUTTON.OLEMSGBUTTON_OK,
                       OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                       OLEMSGICON.OLEMSGICON_INFO,
                       0,        // false
                       out result));
			 * */
			#endregion

			if (null == sender) { return; }
			 // Use the textmanager to help retrieve the active code view
             IVsTextView textView = null;
             IVsTextManager2 textManager = (IVsTextManager2)GetService(typeof(SVsTextManager));

			 if (ErrorHandler.Succeeded(textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out textView)))
			 {
				 // retrieve the view's buffer ServiceProvider.GetService
				 IComponentModel componentModel = (IComponentModel)GetService(typeof(SComponentModel));
				 IVsEditorAdaptersFactoryService adaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
				 var activeTextView = adaptersFactoryService.GetWpfTextView(textView);
				 var textSelection = activeTextView.Selection;

				 Debug.WriteLine(textSelection);

				 using (var edit = activeTextView.TextBuffer.CreateEdit())
				 {
					 var text = textSelection.StreamSelectionSpan.GetText();
					 var xDoc = new XmlDocument();
					 xDoc.PreserveWhitespace = true;
					 try
					 {
						 xDoc.LoadXml(text);
						 Sort(xDoc);
						 Span? firstSpan = null;
						 foreach (var span in textSelection.SelectedSpans)
						 {
							 if (!firstSpan.HasValue)
							 {
								 firstSpan = span;
							 }
							 else
							 {
								 edit.Replace(replaceSpan: span, replaceWith: String.Empty);
							 }
						 }

						 if (firstSpan.HasValue)
						 {
							 var ox = xDoc.OuterXml;
						     var replaceResult = edit.Replace(firstSpan.Value, ox);
							 Debug.WriteLine("Replace returned {0}", replaceResult);
							 edit.Apply();
						 }
					 }
					 catch (XmlException xe)
					 {
						 Debug.WriteLine("{0}: {1}", xe.GetType(), xe.Message);
					 }

				 }
			 }
		}

		private readonly String[] ComparableAttributes = new String[] { "Order", "ID", "Id", "id", "Name", "name" };

		/// <summary>
		/// Sorts the document passed in. If there is only one child node, it will sort the grand children nodes
		/// </summary>
		/// <param name="xDoc"></param>
		public void Sort(XmlDocument xDoc)
		{
			var childNodes = xDoc.ChildNodes;
			if (childNodes.Count == 1)
			{
				childNodes = childNodes[0].ChildNodes;
			}
			var sortableChildList = new List<XmlLinkedNode>(Math.Max(2, childNodes.Count));
			var whiteSpaceChildren = new List<XmlLinkedNode>(Math.Max(2, childNodes.Count));
			List<XmlNode> strangeChildren = null;
			var strangeChildrenLookup = new Dictionary<XmlLinkedNode, List<XmlNode>>();
			var childrenCollectionIndexes = new List<XmlLinkedNode>[childNodes.Count];
			for (int childIndex = 0; childIndex < childNodes.Count; childIndex++)
			{
				var child = childNodes[childIndex];
				if (child is XmlWhitespace)
				{
					// White space following a comment probably should stick with the comment
					if (null == strangeChildren)
					{
						whiteSpaceChildren.Add((XmlWhitespace)child);
						childrenCollectionIndexes[childIndex] = whiteSpaceChildren;
					}
					else
					{
						strangeChildren.Add(child);
					}
				}
				else if(child is XmlElement)
				{
					sortableChildList.Add((XmlElement)child);
					childrenCollectionIndexes[childIndex] = sortableChildList;
					if (null != strangeChildren)
					{
						strangeChildrenLookup.Add((XmlLinkedNode)child, strangeChildren);
						strangeChildren = null;
					}
				}
				else
				{
					if (null == strangeChildren) { strangeChildren = new List<XmlNode>(); }
					strangeChildren.Add(child);
				}
			}

			sortableChildList.Sort((a, b) =>
			{
				XmlElement x = (XmlElement)a;
				XmlElement y = (XmlElement)b;
				int comparison = x.Name.CompareTo(y.Name);
				if (comparison != 0)
				{
					return comparison;
				}

				bool comparedFirst = false;
				foreach (var attributeName in ComparableAttributes)
				{
					if (x.HasAttribute(attributeName) && y.HasAttribute(attributeName))
					{
						var xAttribute = x.Attributes[attributeName];
						var yAttribute = y.Attributes[attributeName];
						if (xAttribute == x.Attributes[0])
						{
							comparedFirst = true;
						}
						int xInt;
						int yInt;
						if (int.TryParse(xAttribute.Value, out xInt) && int.TryParse(yAttribute.Value, out yInt))
						{
							if (xInt > yInt) { return 1; }
							else if (yInt > xInt) { return -1; }
						}
						else
						{
							comparison = String.Compare(xAttribute.Value, yAttribute.Value);
							if (comparison != 0)
							{
								return comparison;
							}
						}
					}
				}

				if (x.HasAttributes && y.HasAttributes && !comparedFirst)
				{
					comparison = String.Compare(x.Attributes[0].Value, y.Attributes[0].Value);
					return comparison;
				}

				return 0;
			});

			XmlNode change = xDoc.ChildNodes.Count == 1 ? xDoc.ChildNodes[0] : xDoc;
			var attributeCollection = new List<XmlAttribute>();
			if (null != change.Attributes)
			{
				foreach (var att in change.Attributes)
				{
					attributeCollection.Add((XmlAttribute)att);
				}
			}
			change.RemoveAll();
			foreach (var at in attributeCollection)
			{
				change.Attributes.Append((XmlAttribute)at);
			}

			for (int childIndex = 0; childIndex < childrenCollectionIndexes.Length; childIndex++)
			{
				var childCollection = childrenCollectionIndexes[childIndex];
				if (null == childCollection) { continue; }
				if (strangeChildrenLookup.ContainsKey(childCollection[0]))
				{
					foreach (var sc in strangeChildrenLookup[childCollection[0]])
					{
						change.AppendChild(sc);
					}
				}
				change.AppendChild(childCollection[0]);
				childCollection.RemoveAt(0);
			}
		}
    }
}
